<?php

namespace App\Http\Controllers;

use App\Http\Helpers\GeeLib;
use App\Http\Helpers\Mail;
use App\Http\Helpers\Sign;
use App\Http\Helpers\Sms;
use App\Http\Services\MsgService;
use App\Models\SmsCodeRecord;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use phpDocumentor\Reflection\Location;
use App\Http\Services\MailService;
use App\Http\Services\LoginService;


class LoginController extends Controller
{

    /**
     *PC登录
     * @author: lican<364548233@qq.com>
     */
    public function login(Request $request){

        $wxcode = trim($request->input('wxcode')); //兼容微校单点登录
        $schoolCode = trim($request->input('state'));
        $res = LoginService::weixiaoLogin($wxcode, $schoolCode);
        if($res['code'] == 0){
            $manager = $res['data'];
            $list = LoginService::getlist($manager);
            $add = LoginService::getAdd($manager);

            $tool = "http://9.135.13.105/admin/tool/index";
            return view('admin.index.index', compact('manager', 'list', 'add', 'tool'));
        }
        return $res;
    }

    /**
     *登出
     * @author: lican<364548233@qq.com>
     */
    public function logout(Request $request){
        $redirectUri = '/login';
        $key = PREFIX . '_auth';
        setcookie($key, '', 0, '/');
        header("location:{$redirectUri}");
//        return MsgService::getMsg(0, ['redirect_uri' => $redirectUri]);
    }

    /**
     *注册
     * @author lican<364548233@qq.com>
     */
    public function register(Request $request){
        $this->validate($request, [
            'name' => 'required',
            'password' => 'required',
            'code' => 'required|int',
            'type' => 'required|int'
        ]);
        $name = trim($request->input('name'));
        $password = trim($request->input('password'));
        $type = (int)$request->input('type'); // 1：手机号注册  0：邮箱注册
        $mobile = trim($request->input('mobile')) ?? '';
        $email = trim($request->input('email')) ?? '';
        $code = trim($request->input('code'));

        $res = LoginService::register($name, $password, $type, $mobile, $email, $code);
        return $res;
    }

    /**
     *短信发送
     * @author: lican<364548233@qq.com>
     */
    public function sendSms(Request $request)
    {
        $this->validate($request, [
            'mobile' => 'required'
        ]);
        $mobile = trim($request->input('mobile'));
        $res = Sms::sendCode($mobile);
        return $res;
    }

    /**
     *邮箱验证码发送
     * @author lican<364548233@qq.com>
     */
    public function sendEmail(Request $request){
        $this->validate($request, [
            'email' => 'required'
        ]);
        $email = trim($request->input('email'));
        $res = MailService::sendEmail($email);
        return $res;
    }

    public function loginConfirm(Request $request){

        $code = $request->input('code');
        if(!empty($code)){
            $user = $this->app->oauth->setRequest($request)->user();
            $userInfo = $user->getOriginal();
            if($userInfo){
                return redirect('index');
            }
        }else{
            echo 2;
            $response = $this->app->oauth->scopes(['snsapi_userinfo'])
                ->redirect($request->fullUrl());
            return $response;
        }
    }

    /**
     *验证码
     * @author lican<364548233@qq.com>
     */
    public function verifyCode(Request $request)
    {
        header('access-Control-Allow-Origin:*');
        $GtSdk = new GeeLib(env('CAPTCHA_ID'), env('PRIVATE_KEY'));
        $data = array(
            "user_id" => "test", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "39.108.116.54" # 请在此处传输用户请求验证时所携带的IP
        );
        echo $this->stepFirst($GtSdk, $data);
    }

    /**
     *核验验证码
     * @author lican<364548233@qq.com>
     */
    public function checkCode($info)
    {
        $GtSdk = new GeeLib(env('CAPTCHA_ID'), env('PRIVATE_KEY'));
        $data = array(
            "user_id" => "test", # 网站用户id
            "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
            "ip_address" => "39.108.116.54" # 请在此处传输用户请求验证时所携带的IP
        );
        return $this->stepTwo($GtSdk, $data, $info);
    }

    public function stepFirst($GtSdk, $data)
    {
        $status = $GtSdk->pre_process($data, 1);
        $_SESSION['gtserver'] = $status;
        $_SESSION['user_id'] = $data['user_id'];
        return $GtSdk->get_response_str();
    }

    public function stepTwo($GtSdk, $data, $info)
    {
        if (isset($info['gtserver']) && $info['gtserver'] == 1) {   //服务器正常
            $result = $GtSdk->success_validate($info['geetest_challenge'], $info['geetest_validate'], $info['geetest_seccode'], $data);
            if ($result) {
                return ['code' => 0];
            } else {
                return ['code' => -1];
            }
        } else {  //服务器宕机,走failback模式
            if ($GtSdk->fail_validate($info['geetest_challenge'], $info['geetest_validate'], $info['geetest_seccode'])) {
                return ['code' => 0];
            } else {
                return ['code' => -1];
            }
        }
    }

    public function test(){
        $res = setcookie('name', 'lican', time() + 86400, '/');
        var_dump($res);
    }

    public function test1(){
        var_dump($_COOKIE);
    }

    public function log(Request $request){
        Sign::writeLog('通知：', $request->except('s'), 'notice');
        return MsgService::getMsg(0);
    }

}
